<template>
  <div class="content-wrap content-container">
    <!-- 标题 -->
    <div class="title-top-box">
      <p class="title">创建需求</p>
    </div>
    <!-- 创建需求 -->
    <div class="create-box">
      <el-form 
        class="create-form" 
        ref="ruleCreateFormRef"
        :rules="createRules"
        :model="createRequirementForm">
        <!-- 项目名称 -->
        <el-form-item
          label="项目名称："
          required
          style="width: 50%"
          prop="projectId"
        >
          <el-select
            v-model="createRequirementForm.projectId"
            filterable="true"
            placeholder="项目名称"
            fit-input-width
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="item in allProjectLists"
              :key="item.id"
              :label="item.projectName"
              :value="item.id"
            />
          </el-select>
          <el-icon
            class="add-icon"
            :size="24"
            @click="dialogAddProVisible = true"
            ><CirclePlus
          /></el-icon>
        </el-form-item>
        <!-- 需求类型 -->
        <el-form-item
          label="需求类型："
          required
          style="width: 50%;"
          prop="projectType"
        >
          <el-radio-group v-model="createRequirementForm.projectType">
            <el-radio-button
              v-for="item in allTypeLists"
              :key="item.id"
              :label="item.type"
              :value="item.id"
            />
          </el-radio-group>
        </el-form-item>
        <!-- 需求标题 -->
        <el-form-item
          label="需求标题："
          required
          style="width: 50%"
          prop="projectTitle"
        >
          <el-input
            v-model="createRequirementForm.projectTitle"
            placeholder="请输入需求标题"
            style="width: 400px"
          ></el-input>
        </el-form-item>
        <!-- 审核人 -->
        <el-form-item
          v-if="isAuthorityId == '444'"
          label="审核人："
          style="width: 20%;"
          required
          prop="itemRequirementBossNameUUID"
        >
        <el-select
            v-model="createRequirementForm.itemRequirementBossNameUUID"
            placeholder="请选择审核人"
            filterable
            clearable
            style="width: 160px; min-width: 100px;">
            <el-option
              v-for="(item, index) in allRoleUserList"
              :key="index"
              :label="item.nickName"
              :value="item.uuid"
            />
          </el-select>
        </el-form-item>  
        <!-- 预计上线时间 -->
        <el-form-item label="预计上线时间：" prop="onlineTime" style="width: 30%" required>
          <el-date-picker
            style="width: 180px"
            v-model="createRequirementForm.onlineTime"
            type="date"
            placeholder="请选择预计上线日期"
            :disabledDate="disabledDate"
          />
        </el-form-item>
        <!-- 需求详情 -->
        <el-form-item
          label="简述需求："
          required
          style="width: 100%; margin-bottom: 20px;"
          prop="projectMsg"
        >
          <div style="width: 100%;">
            <Toolbar style="height: 41px; border: 1px solid #ddd" :editor="editorRef" :defaultConfig="toolbarConfig" />
            <Editor style="height: 320px; border: 1px solid #ddd; overflow: auto" v-model:modelValue="valueHtml" :defaultConfig="editorConfig"
            @onChange="handleChange" @onCreated="handleCreated" />
          </div>
        </el-form-item>
        <!-- 上传文件 -->
        <el-form-item
          v-if="!(isAuthorityId == '555' || isAuthorityId == '666' || isAuthorityId == '777' || isAuthorityId == '111')"
          class="upload-box"
          label="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;附件:"
          prop="filePaths"
        >
          <div style="width: 100%;">
            <el-upload 
              class="upload-demo"
              v-model:file-list="fileList"
              action=""
              multiple="true"
              :limit="3"
              :http-request="handleUpLoad"
              :on-success = "handleSuccess"
              :on-error="handleError"
              :on-remove = "handleRemove"
              :on-exceed = "handleExceed"
              >
              <el-button class="upload-btn" type="Default" size="small">+</el-button>
            </el-upload>
          </div>
        </el-form-item>

        <!-- 创建需求 -->
        <el-form-item class="create-button">
          <el-button type="primary" @click="handleResetRequirement">重置</el-button>
          <el-button type="primary" @click="handleCreateRequirement(ruleCreateFormRef)">创建</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 添加项目名称对话框 -->
    <el-dialog
      id="dialogForm"
      style="width: 400px; margin-top: 200px"
      v-model="dialogAddProVisible"
      title="添加项目"
      :close-on-click-modal="false"
      :show-close="true"
      :before-close="handleBeforeCancel"
    >
      <el-input
        placeholder="请输入项目名称"
        v-model="newProjectName"
      ></el-input>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleAddProjectDialog">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加需求类型对话框 -->
    <!-- <el-dialog
      id="dialogForm"
      style="width: 400px; margin-top: 200px"
      v-model="dialogAddReqTypeVisible"
      title="添加需求类型"
      :show-close="true"
      :before-close="handleBeforeCancel"
    >
      <el-input
        placeholder="请输入需求类型"
        v-model="newProjectType"
      ></el-input>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleAddTypeDialog">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog> -->
  </div>
</template>

<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { IDomEditor } from '@wangeditor/editor';
import { ref, onMounted, reactive, onBeforeUnmount, shallowRef } from "vue";
import type { FormInstance } from 'element-plus';
import { ElMessage, ElMessageBox } from "element-plus";
import useCommonDataStore from "@/store/common/common";
// import useUserStore from "@/store/modules/user";
import {
  postAddItmeItem,
  postCreateRequirement,
} from "@/api/newDemands/index";
import { postUploadFile } from "@/api/common/index";
import { isValidateEditor } from "@/utils/utils";
import { useRouter } from "vue-router";



interface AllProjectLists {
  id: number;
  projectName: string;
}
interface AllTypeList {
  id: number;
  type: string;
  bgColor: string;
}
interface AllRoleUserList {
  nickName: string;
  headerImg: string;
  uuid: string;
}
interface CreateRequirementForm {
    projectId: number | null,
    projectType: number | null,
    projectTitle: string,
    itemRequirementBossNameUUID: string | null,
    onlineTime: string | null,
    projectMsg: string,
    filePaths: Array<[String]>
}


// const excessStyle = { color: "#f56a00", backgroundColor: "#fde3cf" };
const loading = ref(false);
let useCommonStore = useCommonDataStore();
// let userStore = useUserStore();
let router = useRouter();

const allProjectLists = ref<AllProjectLists[]>([]); // 定义所有项目名称列表
const allTypeLists = ref<AllTypeList[]>([]); // 定义所有项目名称列表
const allRoleUserList = ref<AllRoleUserList[]>([]); // 定义所有研发人员列表

const dialogAddProVisible = ref(false); //添加项目名称弹窗控件
const newProjectName = ref(""); // 临时存储新项目名称
// const isExamineUser = ref<any>();// 是否为审核人
const fileList = ref<any>([]);//已上传的附件
const filePaths = ref([]);//所有上传文件响应地址
const isAuthorityId = ref<any>();//当前用户的权限ID

// 表单实例
const ruleCreateFormRef = ref<FormInstance>();
// 表单数据初始值
const createRequirementForm = reactive<CreateRequirementForm>({
    projectId: null,
    projectType: null,
    projectTitle: "",
    itemRequirementBossNameUUID: "",
    onlineTime: null,
    projectMsg: "",
    filePaths: []
});

// 表单验证规则
const createRules = reactive({
    projectId: [{ required: true, message: "请选择项目名称", trigger: "blur" }],
    projectType: [{ required: true, message: "请选择需求类型", trigger: "blur" }],
    projectTitle: [{ required: true, message: "请输入需求名称", trigger: "blur" }],
    onlineTime: [{ required: true, message: "请选择预计上线时间", trigger: "blur" }],
    itemRequirementBossNameUUID: [{
       required: true, 
       message: "请选择审核人", 
       trigger: "blur",
      }], 
    projectMsg: [{ 
      required: true, 
      message: "请输入需求详情", 
      trigger: "blur", 
      // @ts-ignore
      validator: (rule: any, value: any, callback: any) => {
        // 调用自定义验证函数
        if (isValidateEditor(value)) {
          callback(new Error("需求详情不能为空格或空行！"));
        } else {
          callback();
        }
      }
    }], 
    // filePaths: [{ required: true, message: "请上传需求草稿", trigger: "blur" }]
});


// 获取公共数据
const getCommon = async (index: any) => {
  // await userStore.getUseInfo();
  await useCommonStore.getAllReqTypesList();
  await useCommonStore.getAllProjectList();
  await useCommonStore.getAllRoleUsersList(index);

  isAuthorityId.value = localStorage.getItem("authorityId");

  allProjectLists.value = useCommonStore.$state.allProjectList;
  allTypeLists.value = useCommonStore.$state.allReqTypesList;
  allRoleUserList.value = useCommonStore.$state.allRoleUserList;
};

// TODO 添加项目功能
const handleAddProjectDialog = async () => {
  loading.value = true;

  // 验证newProjectName是否为空
  if (newProjectName.value.trim() === "") {
    alert("请输入项目名称");
    return;
  } else if (
    allProjectLists.value.some(
      (item: any) => item.projectName === newProjectName.value
    )
  ) {
    alert("该项目已创建，请直接选择！");
    return;
  } else {
    // 发起添加项目请求
    const { data } = await postAddItmeItem({
      itemName: newProjectName.value,
    });
    if (data.code === 200) {
      dialogAddProVisible.value = false;
      ElMessage.success(data.msg);
      await getCommon(777);
      createRequirementForm.projectId = allProjectLists.value[allProjectLists.value.length-1].id;
      loading.value = false;
    } else {
      ElMessage.error(data.msg);
      dialogAddProVisible.value = false;
      loading.value = false;
      throw console.error(data.msg);
    }
  }
};

// 取消/关闭添加项目/需求类型功能
const handleCancel = () => {
  dialogAddProVisible.value = false;
  newProjectName.value = "";
};
const handleBeforeCancel = (done: any) => {
  dialogAddProVisible.value = false;
  newProjectName.value = "";
  done();
};

// TODO 规定预计上线时间为today及之后，之前的不可选
const disabledDate = (time: any) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return time.getTime() < today.getTime();
};


// ! 自定义上传文件
const handleUpLoad = (options: any) => {
  console.log("Options:", options);
  postUploadFile(options.file, "draftPath", "1").then(res => {
    // console.log("上传结果：", res);
    options.onSuccess(res);
  }).catch(error => {
    // console.log("上传失败：", error);
    // ElMessage.error(error);
    options.onError(error);
  })
};


const handleSuccess = (v: any) => {
  // console.log("上传成功：", v.data.data)
  if (v.data.data && v.data.data.resultFilePath) {
    // @ts-ignore
    filePaths.value.push(v.data.data);
  }
  // console.log("filePath:", filePaths.value);
};

const handleError = (err: any) => {
  // console.log("上传失败：", err);
  ElMessage.error(err);
};

const handleRemove = (v: any) => {
  // console.log("删除文件：", v);
  fileList.value = fileList.value.filter((item: any) => item.name !== v.name);
  filePaths.value = filePaths.value.filter((path: any) => path.fileName !== v.name);
  // console.log("剩余文件", fileList.value);
  // console.log("删除后的文件：", filePaths.value);
};

const handleExceed = (exc: any) => {
  ElMessage.warning("最多上传3个文件！")
};


// TODO 需求详情-富文本编辑器
const editorRef = shallowRef();
const valueHtml = ref("");
const toolbarConfig = { toolbarKeys: ["uploadImage"] };
const editorConfig =  {
  placeholder: "请输入内容...",
  showLinkImg: false,
  scroll: true,
  // 上传图片配置
  MENU_CONF: {
    uploadImage: {
      server: "/saferycom/file/upload_file",
      fieldName: "file",
      allowedFileTypes: ["image/*"],
      uploadImgMaxSize: 10 * 1024 * 1024, // 设置图片最大上传大小为10MB
      maxFileSize: 10 * 1024 * 1024, // 设置文件大小限制为10MB
      customInsert: async (res: any, insertFn: any) => {
        if (res.code === 200) {
          insertFn(res.data.resultFilePath); //上传到服务器
        } else {
          ElMessage.error("上传图片失败");
          throw new Error();
        }
      },
      customPaste: async (editor:any, event:any) => {
        const items = event.clipboarData.items;
        for (let item of items) {
          if(item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile();
            const formData = new FormData();
            formData.append('file', file);
            fetch("/saferycom/file/upload_file", {
              method: "POST",
              body: formData,
            })
            .then(response => response.json())
            .then(result => {
              editor.cmd.do('insertHtml',`<img src="${result.resultFilePath}"/>`);
            })
            .catch(error => {
              ElMessage.error("粘贴图片上传失败",error);
              event.preventDefault();
            });
          }
        }
        event.preventDefault();
        return false;
      },
    },
  },
};

onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
};

const handleChange = (editor: IDomEditor) => {
  const data = editor.getHtml();

  // 解析HTML字符串为DOM
  const parser = new DOMParser();
  const doc = parser.parseFromString(data, 'text/html');

  // 获取所有的img标签
  const images = doc.querySelectorAll('img');

  // 为每个img标签添加style属性
  images.forEach(img => {
  img.setAttribute('style', 'width: 30%;');
  });

  // 将修改后的DOM转换回字符串
  const modifiedData = doc.body.innerHTML;

  createRequirementForm.projectMsg = modifiedData;
};


// TODO 点击创建需求功能
const handleCreateRequirement = async (formEl: FormInstance | undefined) => {
    loading.value = true;
    // createRequirementForm.filePaths = fileList.value.map((item: any) => item.resultFilePath);
    if(filePaths.value.length !== 0) {
      createRequirementForm.filePaths = filePaths.value.map((path: any) => path.resultFilePath);
    }
    console.log("请求参数：", createRequirementForm);

    if (!formEl) {
      console.error("表单验证失败，请将内容填写完整");
      return;
    };
  
    // 表单验证
    const validatePromise = formEl.validate();
    try {
      await validatePromise;
      // 表单验证成功
      await ElMessageBox.confirm("确定要创建需求吗？","确定", {
        cancelButtonText:"取消",
        confirmButtonText:"确定",
        type:"warning",
      }).then(async () => {
        //* 处理请求参数
        const reqData = {
          projectId: createRequirementForm.projectId,
          projectType: createRequirementForm.projectType,
          projectTitle: createRequirementForm.projectTitle,
          // itemRequirementBossNameUUID: createRequirementForm.itemRequirementBossNameUUID == "" ? "" : createRequirementForm.itemRequirementBossNameUUID,
          // itemRequirementBossNameUUID: isExamineUser.value ? userStore.$state.userInfo.uuid : createRequirementForm.itemRequirementBossNameUUID,
          itemRequirementBossNameUUID: createRequirementForm.itemRequirementBossNameUUID,
         /*  itemRequirementChilds: createRequirementForm.itemRequirementChilds.map((item: any) => {
            return {
              userUUID: item.userUUID,
              isBoss: 1
            }
          }), */
          onlineTime: createRequirementForm.onlineTime,
          projectMsg: createRequirementForm.projectMsg,
          filePaths: createRequirementForm.filePaths
        };
  
  
        const  { data } = await postCreateRequirement(reqData);
        if (data.code === 200) {
          loading.value = false;
          ElMessage.success(data.msg);
          router.push("/requirement/userCreate");
        } else {
          loading.value = false;
          ElMessage.error(data.msg);
          throw console.log(data.msg);
        }

      }).catch(async () => {
       console.log("取消创建需求操作！");
      });
    } catch (error) {
      // 表单验证失败
      loading.value = false;
      console.error("表单验证失败，请将内容填写完整");
      return;
    }
};

// const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
//   return ElMessageBox.confirm(
//     `Cancel the transfer of ${uploadFile.name} ?`
//   ).then(
//     () => true,
//     () => false
//   )
// }

// TODO 重置需求
const handleResetRequirement = () => {
  // 表单数据初始值
  createRequirementForm.projectId = null;
  createRequirementForm.projectType = null;
  createRequirementForm.projectTitle = "";
  createRequirementForm.itemRequirementBossNameUUID = "";
  createRequirementForm.onlineTime = null;
  // createRequirementForm.filePaths = [];
  // createRequirementForm.projectMsg = "";
  valueHtml.value = "";
  fileList.value = [];
  filePaths.value = [];
};

onMounted(() => {
  getCommon(333);
  setTimeout(() => {
    valueHtml.value = "";
  }, 1500);
});
</script>
<style lang="scss" scoped>
.content-container {
  background-color: white;
  display: flex;
  flex-direction: column;
  padding: 10px;
  /* 标题样式 */
  .title-top-box {
    width: 100%;
    height: 40px;
    margin-bottom: 20px;
    .title {
      width: 100%;
      font-size: 24px;
      font-family: Arial, Helvetica, sans-serif;
      border-bottom: 1px solid #dcdfe6;
      color: #000;
    }
  }
  /* 创建需求 */
  .create-box {
    height: 100%;
    overflow: auto;
    .create-form {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      .add-icon {
        color: #dcdfe6;
        cursor: pointer;
        margin-left: 5px;
      }
      .add-icon:hover {
        color: #409eff;
      }
      .is-check-role {
        background-color: #409eff;
      }

      .upload-box {
        width: 100%;
        // height: 100px;
        .el-form-item__content {
          align-content: flex-start;
        }
      }
    }
    .create-form > *:not(.create-button) {
      order: 1;
    }
    .create-button {
      order: 2;
      margin-left: auto;
      margin-right: 10px;
      margin-top: 10px;
    }
  }
}
</style>
<style>
.el-upload {
  --el-upload-dragger-padding-horizontal: 0px;
  .el-upload-dragger .el-icon--upload {
    margin-top: 10px;
  }
}
.el-form-item__content {
  align-content: flex-start;
}
.upload-demo {
  align-content: flex-start;
}
.el-form-item__label {
  font-weight: bold;
}
.el-radio-button {
  border-radius: 0;
  margin-right: 10px;
  border: none;
}
.el-radio-button:first-child .el-radio-button__inner,
.el-radio-button:last-child .el-radio-button__inner {
  border-radius: 5px;
}
.el-radio-button .el-radio-button__inner {
  border: 1px solid #dcdfe6;
  border-radius: 5px;
}
</style>
